<?php

namespace App\Http\Middleware;

use Closure;
use Encone\Logs\Models\Logs;
use Illuminate\Support\Facades\Session;
use Zhuzhichao\IpLocationZh\Ip;

class ActionLogs
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Session::get('admin.username'))
        {
            $username = Session::get('admin.username');
            $id = Session::get('admin.id');
        }else{
            $username = $request->username;
            $id = 0;
        }
        $str = '';
        $address = Ip::find($request->getClientIp());
        if(count($address)){
            if($request->getClientIp() == '127.0.0.1'){
                $str = '本地';
            }else{
                foreach($address as $k=>$item){
                    if($k < 3){
                        if($item)
                        {
                            $str .= $item;
                        }
                    }
                }
            }
        }
//        $description = $username.'|'.$request->path().'|'.json_encode($request->all());
        if($request->method() == 'GET') {
            $description = '用户：'.$username . ' | 请求：' . $request->path();
        }else{
            $description = '用户：'.$username . ' | 请求：' . $request->path() . ' | 数据：' . json_encode($request->all());
        }
     //   Logs::createLog(['admin_user_id'=>$id,'method'=>$request->method(),'route'=>$request->path(),'ip'=>$str.'|'.$request->getClientIp(),'description'=>$description]);
        return $next($request);
    }
}
